//
//  BaseImageBrowserVC.swift
//  Health-Doctor
//
//  Created by 勇胡 on 2023/2/6.
//  Copyright © 2023 掌上卫健. All rights reserved.
//图片浏览器 基类

import Foundation
import UIKit

class BaseImageBrowserVC: Lantern {
    //即将销毁
    public var onWillDismissBlock: (()->())?
    //图片地址
    public var imgUrls:[String] = []
    public var imgList:[UIImage] = []
    
    /// 显示图片浏览器
    /// - Parameters:
    ///   - imgUrls: 图片地址
    ///   - index: 显示指定图片
    public func show(imgList:[UIImage],index:Int = 0){
        if imgList.isEmpty{return}
        self.imgList = imgList
        // 浏览过程中实时获取数据总量
        self.numberOfItems = {[weak self] in
            guard let `self` = self else { return 0}
            return self.imgList.count
        }
        // 刷新Cell数据。本闭包将在Cell完成位置布局后调用。
        self.reloadCellAtIndex = {[weak self] context in
            guard let `self` = self else { return }
            let lanternCell = context.cell as? LanternImageCell
            let img = self.imgList[context.index]
            lanternCell?.imageView.image = img
        }
        self.pageIndex = index
        self.show()
    }
    
    
    //刷新（当新增图片或删除图片后）
    public func refresh() {
        
        let count = self.imgUrls.count
        if count == 0{//没有图片，就自动退出
            guard let _ = self.navigationController?.popViewController(animated: true) else {
                self.dismiss(animated: true)
                return
            }
            return
        }
        if self.pageIndex < 0{
            self.pageIndex = 0
        }else if count > self.pageIndex{//下一张
            //..
        }else if count > (self.pageIndex-1){//上一张
            pageIndex = pageIndex-1
        }
        for suView in self.browserView.scrollView.subviews{
            suView.removeFromSuperview()
        }
        
        self.reloadData()
        self.browserView.resetContentSize()
        self.browserView.resetCells()
        self.browserView.reloadItems()
        self.reloadData()
        
    }
    
    override func dismiss(){
        super.dismiss()
        onWillDismissBlock?()
    }
    
}
